
package com.elvin.platform.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.elvin.platform.beans.User;
import com.elvin.platform.beans.UserInfo;
import com.elvin.platform.service.UserService;
import com.elvin.platform.util.HttpUtil;
import com.elvin.platform.util.Result;
import io.swagger.annotations.ApiParam;
import net.glxn.qrgen.javase.QRCode;
import net.glxn.qrgen.core.image.ImageType;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Controller
@RestController
@RequestMapping("/wechat")
public class WechatController {
  @Resource
  private UserService userService;
  // 保存扫码状态的map，用于轮询检查用户是否已经扫码
  private static Map<String, Boolean> scanStatusMap = new ConcurrentHashMap<>();

  // 生成随机字符串，用于作为state参数
  private String generateState() {
    return UUID.randomUUID().toString().replace("-", "");
  }

  // 生成授权链接，用于生成二维码
  private String generateAuthUrl(String redirectUri, String state) {
    String appId = "wx90c014a4624eaf04"; // 替换为自己的appId
    return "https://open.weixin.qq.com/connect/qrconnect?appid=" + appId +
        "&redirect_uri=" + redirectUri +
        "&response_type=code" +
        "&scope=snsapi_login" +
        "&state=" + state +
        "#wechat_redirect";
  }

  // 生成二维码
  @GetMapping("/login")
  public void generateQRCode(HttpServletResponse response) throws Exception {
    // 生成随机字符串，用于作为state参数
    String state = generateState();
    // 将扫码状态保存到map中
    scanStatusMap.put(state, false);
    // 生成授权链接，用于生成二维码
    String redirectUri = URLEncoder.encode("https://ecmp.elviniot.net", "UTF-8");
    String authUrl = generateAuthUrl(redirectUri, state);
    // 生成二维码
    ByteArrayOutputStream out = QRCode.from(authUrl).to(ImageType.PNG).stream();

    response.setContentType("image/png");
    response.setContentLength(out.size());
    response.getOutputStream().write(out.toByteArray());
    response.getOutputStream().flush();
    response.getOutputStream().close();
  }


  // 检查用户是否已经扫码
 /* @GetMapping("/checkScan2")
  public ApiResponse checkScan2(String state) {
    Boolean scanStatus = scanStatusMap.get(state);
    if (scanStatus == null) {
      return ApiResponse.ofMessage(ApiResponse.ResponseCode.INVALID_PARAM, "invalid state");
    } else if (scanStatus) {
      // 用户已经扫码，返回code和state
      String code = "your_code"; // 替换为自己的code
      scanStatusMap.remove(state);
      return ApiResponse.ofSuccess(new HashMap<String, String>() {{
        put("code", code);
        put("state", state);
      }});
    } else {
      // 用户还未扫码
      return ApiResponse.ofSuccess();
    }
  }*/

  // 检查用户是否已经扫码
  @GetMapping("/checkScan")
  public Result<Object> checkScan(String state) {
    Result<Object> result = new Result<>();
    Boolean scanStatus = scanStatusMap.get(state);
    if (scanStatus == null) {
      result.fail(null,"invalid state");
      return result;
    } else if (scanStatus) {
      // 用户已经扫码，返回code和state
      String code = "your_code"; // 替换为自己的code
      scanStatusMap.remove(state);

      result.success(null,"用户已经扫码");
      result.setData(new HashMap<String, String>() {{
        put("code", code);
        put("state", state);
      }} );
      return result;

    } else {
      // 用户还未扫码
      result.success(null,"用户还未扫码！");
      return result;
    }
  }

  // 接收回调，获取code和state
  @GetMapping("/callback")
  public   Result<Object> callback(String code, String state) {
    Result<Object> result = new Result<>();
    String openId = getOpenId(code);
    UserInfo userRes = getUserInfoByOpenDb(openId);
    result.success(userRes.getUser(),"登录成功！");
    return result;
  }
  public UserInfo getUserInfoByOpenDb(String openId) {
    EntityWrapper<User> wrapper = new EntityWrapper<>();
    wrapper.eq("openid", openId);
    User userDb = userService.selectOne(wrapper);
    return new UserInfo(userDb);
  }

  public String getOpenId(String code) {
        String appId = "wx90c014a4624eaf04";
        String appSecret = "c0adb20f942be9a424634ad4a2ad689e";
        String grantType = "authorization_code";
        Map<String, String> requestUrlParam = new HashMap<>();
        requestUrlParam.put("appid", appId); // 开发者设置中的appId
        requestUrlParam.put("secret", appSecret); // 开发者设置中的appSecret
        requestUrlParam.put("js_code", code); // 小程序调用wx.login返回的code
        requestUrlParam.put("grant_type", grantType); // 默认参数
        JSONObject json = JSONObject.parseObject(HttpUtil.sendPost("https://api.weixin.qq.com/sns/jscode2session", requestUrlParam));
        String openid = json.getString("openid");
        return openid;
  }

}


